Program to Convert Binary to Decimal in Java 您所在的位置:网站首页 convert binary to hexadecimal manually Program to Convert Binary to Decimal in Java

Program to Convert Binary to Decimal in Java

2022-05-08 13:06| 来源: 网络整理| 查看: 265

Here you will get program to convert binary to decimal in Java.

There are mainly two ways to convert a binary number to decimal number in Java.

1. By using parseInt() method of Integer class.2. By using user defined logic.

Program to Convert Binary to Decimal in Java

By using Integer.parseInt()

Integer.parseInt() method takes two arguments. First argument is a string and second argument is the base or radix in which we have to convert the number. The output is the integer represented by the string argument in the specified radix. Below is the program for it.

 

123456789101112131415import java.util.Scanner; class BinaryToDecimal{        public static void main(String args[])        {            Scanner s=new Scanner(System.in);                        System.out.println("Enter a binary number:");             String n=s.nextLine();                        System.out.println(Integer.parseInt(n,2));        }}

 

Without using Integer.parseInt()

In this method we have to define our own logic for converting binary number to decimal. The approach that we will use here is mentioned in below example.

binary to decimal example

Image Source

The program that implements above approach is mentioned below.

 

1234567891011121314151617181920212223import java.util.Scanner; class BinaryToDecimal{        public static void main(String args[])        {            Scanner s=new Scanner(System.in);                        System.out.println("Enter a binary number:");            int n=s.nextInt();                        int decimal=0,p=0;                        while(n!=0)            {                decimal+=((n%10)*Math.pow(2,p));                n=n/10;                p++;            }                        System.out.println(decimal);        }}

 

Output

Program to Convert Binary to Decimal in JavaIf you found anything missing or incorrect in above programs then please mention it by commenting below.

You May Also Like:ipconfig vs ifconfig – Difference between ipconfig and ifconfigPL/SQL Program to Find Greatest of Three NumbersPython Program to Check Palindrome NumberDijkstra’s Algorithm in CInnovative Tools You Should Consider for Your Business


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有